package com.vf.core.interceptor;

import java.util.Date;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.vf.core.render.RenderBean;
import com.vf.core.util.UuidUtil;
import com.vf.s.common.model.sys.SysLog;
import com.vf.s.common.plugins.shiro.ShiroKit;
import com.vf.s.common.plugins.shiro.SimpleUser;

public class GlobalActionInterceptor implements Interceptor{
	protected final Log LOG = Log.getLog(getClass());

	public void intercept(Invocation inv) {
		try {
			SysLog log=log(null, inv,"0","");
			//LOG.debug("GlobalActionInterceptor");
			inv.invoke();
			log(log, inv,"0","");
		}catch (Exception e) {
			e.printStackTrace();
			RenderBean renderBean = new RenderBean();
			renderBean.setCode(500);
			renderBean.setMessage("请求异常！");
			inv.getController().renderJson(renderBean);
			//LOG.error("GlobalActionInterceptor");
			log(null, inv,"2",e.getMessage());
		}
	}
	
	private SysLog log(SysLog log,Invocation inv,String type,String remark) {
		if(PropKit.getBoolean("devMode", false)) {
			return null;
		}
		try {
			if(log==null) {
				SimpleUser simpleUser=ShiroKit.getLoginUser();
				log =new SysLog();
				log.setId(UuidUtil.getUUID());
				log.setIp(IpKit.getRealIp(inv.getController().getRequest()));
				log.setMethod(inv.getController().getRequest().getMethod());
				log.setAction(inv.getActionKey());
				log.setType(type);
				log.setRemark(remark);
				if(simpleUser!=null) {
					log.setName(simpleUser.getName());
					log.setOperatorName(simpleUser.getUsername());
					log.setOperatorId(simpleUser.getId());
				}else {
					log.setName("系统");
					log.setOperatorName("系统");
				}
				log.setRequestTime(new Date(System.currentTimeMillis()));
				log.save();
			}
			else {
				log.setResponseTime(new Date(System.currentTimeMillis()));
				if(StrKit.isBlank(remark)) log.setRemark(remark);
				log.update();
			}
			
		}catch (Exception e) {
			LOG.error("记录请求日志异常：", e);
		}
		return log;
	}
}
